//
//  HomeViewController.m
//  Learn
//
//  Created by icomexe on 2018/10/27.
//  Copyright © 2018年 cjg. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeRequest.h"
#import "HomeListRootModel.h"
#import "HomeTopView.h"
#import "BannerCell.h"
#import "QupeiyinCell.h"
#import "JiaocaiCell.h"
#import "KewaikuozhanCell.h"
#import "UIButton+Extension.h"
#import "ChangePlainViewController.h"
#import "ChooseGradeViewController.h"
#import "WordMemoryViewController.h"
#import "WordCardDetailViewController.h"
#import "BookListViewController.h"
#import "BannerDetailViewController.h"
#import "ScanViewController.h"
#import "WrongQuestionBookController.h"
#import "GradeChooseView.h"
#import "ModuleChooseView.h"
#import "StarterModuleViewController.h"

#import "ReciteViewController.h"
#import "ChosseWordViewController.h"
#import "PkViewController.h"
#import "YBZLViewController.h"
#import "MineAPIManager.h"
#import "ShuaWordViewController.h"
@interface HomeViewController ()<UITableViewDataSource , UITableViewDelegate>
{
    __block BOOL showChoose;
}

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) HomeTopView *topView;

@property (nonatomic, strong) HomeListBodyModel *model;

@property (nonatomic, strong) HSchildrenBookModel * currentBook;
@property (nonatomic, strong) HSTextBookUnitModel *currentUnit;
@property (nonatomic, strong) NSMutableArray<HSTextBookModel *> *bookList;
@property (nonatomic, strong) NSMutableArray<HSTextBookUnitModel *> *unitList;
@end

@implementation HomeViewController
//点击屏幕空白处 －－－ 回收键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

-(HomeTopView *)topView {
    if (!_topView) {
        _topView = [[HomeTopView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 5+40)];
        @weakify(self);
        _topView.messageBlock = ^{
            @strongify(self);
            [self.parentViewController pushToViewControllerWithClassName:@"MessageListViewController" animated:YES];
        };
    }
    return _topView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H-60-SafeAreaBottomHeight) style:(UITableViewStyleGrouped)];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        //        _tableView.estimatedRowHeight = 100;
        //        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        [_tableView registerClass:[BannerCell class] forCellReuseIdentifier:@"BannerCell"];
        [_tableView registerClass:[QupeiyinCell class] forCellReuseIdentifier:@"QupeiyinCell"];
        [_tableView registerClass:[JiaocaiCell class] forCellReuseIdentifier:@"JiaocaiCell"];
        [_tableView registerClass:[KewaikuozhanCell class] forCellReuseIdentifier:@"KewaikuozhanCell"];
        
        
    }
    return _tableView;
}

- (void)getdataFromServer{
    
    WS(WeakSelf)
    [HomeRequest getHomeListDataWithParam:nil result:^(HomeListRootModel *listModel) {
        HomeListBodyModel *model = listModel.data;
        WeakSelf.model = model;
        lApp.isVip = model.isVip;
        lApp.bookid = model.bookid;
        [WeakSelf.tableView reloadData];
        [WeakSelf loadBookListData];
    }];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *fileName = [NSString stringWithFormat:@"%@",lApp.useModel.username];
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];
    
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:path]) {
        [fm removeItemAtPath:path error:nil];
    }
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImageView *topbgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_W*344/375)];
    topbgView.image = [UIImage imageNamed:@"homeTopBg"];
    [self.view addSubview:topbgView];
    
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.topView;
    WS(WeakSelf)
    self.topView.searchBlock = ^{
        ScanViewController *vc = [ScanViewController new];
        [WeakSelf.navigationController pushViewController:vc animated:YES];
    };
    [self checkVersion];
   
    
    [MethodTool checkMicrophonePromiss:self];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 15;
    }
    if (section == 1) {
        return 10;
    }
    if (section == 2 && self.currentBook) {
        return 50;
    }
    return CGFLOAT_MIN;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 2 && self.currentBook) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 50)];
        headerView.backgroundColor = [UIColor clearColor];
        UILabel *LB = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, SCREEN_W-20, 50)];
        LB.text = @"教材同步";
        LB.font = FONT_BODY_16;
        LB.textColor = rgbHex(0x333333, 1);
        [headerView addSubview:LB];
        return headerView;
    }
    
    return nil;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return (SCREEN_W-20)*138/355;
    }
    if (indexPath.section == 1) {
        return 400;
    }
    if (indexPath.section == 2 && self.currentBook) {
        return 130;
    }
    return CGFLOAT_MIN;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        BannerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BannerCell"];
        if (!cell) {
            cell = [[BannerCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"BannerCell"];
        }
        NSMutableArray *imas = [NSMutableArray arrayWithCapacity:1];
        for (HomeBannerModel *model in self.model.banner) {
            [imas addObject:model.image];
        }
        cell.imagesURLStrings = imas;
        cell.selectIndexBlock = ^(NSUInteger value) {
            NSLog(@"点击轮播图 ==== %lu",(unsigned long)value);
            BannerDetailViewController *vc = [[BannerDetailViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        return cell;
    }
    
    if (indexPath.section == 1) {
        KewaikuozhanCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KewaikuozhanCell"];
        if (!cell) {
            cell = [[KewaikuozhanCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"KewaikuozhanCell"];
        }
        
        cell.menuItemBlock = ^(NSString * _Nonnull menuName) {
            if ([menuName isEqualToString:@"听说"]) {
                BookListViewController *vc = [[BookListViewController alloc] init];
                vc.title = @"听说";
                vc.type = BookTypeHearsay;
                [self.navigationController pushViewController:vc animated:YES];
            }
            if ([menuName isEqualToString:@"听力"]) {
                [MethodTool goWebviewWithUrl:H5_API_listen];
            }
            if ([menuName isEqualToString:@"跟读"]) {
                [MethodTool goWebviewWithUrl:H5_API_followReading];
//                BookListViewController *vc = [[BookListViewController alloc] init];
//                vc.title = @"跟读";
//                vc.type = BookTypeFollowUpReading;
//                [self.navigationController pushViewController:vc animated:YES];
            }
            if ([menuName isEqualToString:@"笔试"]) {
                [MethodTool goWebviewWithUrl:H5_API_writtenTest];
            }
            if ([menuName isEqualToString:@"音标"]) {
                [MethodTool goWebviewWithUrl:phoneticSymbol];
            }
            if ([menuName isEqualToString:@"黑布林"]) {
                [MethodTool goWebviewWithUrl:H5_API_heibulin];
            }
            if ([menuName isEqualToString:@"典范"]) {
                [MethodTool goWebviewWithUrl:H5_API_mode];
            }
            if ([menuName isEqualToString:@"新概念"]) {
                [MethodTool goWebviewWithUrl:H5_API_newConcept];
            }
            
            if ([menuName isEqualToString:@"趣味"]) {
                BookListViewController *vc = [[BookListViewController alloc] init];
                vc.title = @"趣味";
                vc.type = BookTypeInterest;
                [self.navigationController pushViewController:vc animated:YES];
            }
            if([menuName isEqualToString:@"背单词"]){
                
                [MethodTool goWebviewWithUrl:H5_API_word];
                
            }
            if([menuName isEqualToString:@"刷单词"]){
                
                [MethodTool goWebviewWithUrl:H5_API_brushWords];
                
            }
            if ([menuName isEqualToString:@"错题本"]) {
                [MethodTool goWebviewWithUrl:H5_API_wrongBook];
            }
            if ([menuName isEqualToString:@"单词PK"]) {
                PkViewController *pkVC = [[PkViewController alloc]init];
                pkVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:pkVC animated:YES];
            }
            if ([menuName isEqualToString:@"音标专练"]) {
                [MethodTool goWebviewWithUrl:H5_API_phoneticPractice];
            }
            //            if ([menuName isEqualToString:@"看一看"]) {
            //                [MethodTool goWebviewWithUrl:H5_API_taskLook];
            //            }
        };
        return cell;
    }
    if (indexPath.section == 2) {
        JiaocaiCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JiaocaiCell"];
        if (!cell) {
            cell = [[JiaocaiCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"JiaocaiCell"];
        }
        //        [cell.imView sd_setImageWithURL:[NSURL URLWithString:model.image]];
        NSString *text = self.currentBook ? self.currentBook.book_name : nil;
        [cell.titleLB setTitle:text forState:UIControlStateNormal];
        cell.subTitleLB.text = self.currentUnit ? self.currentUnit.name : nil;
        [cell.imView sd_setImageWithURL:[NSURL URLWithString: [NSString stringWithFormat:@"%@%@",BaseUrl,self.currentBook.coverUrl]] placeholderImage:[UIImage imageNamed:@""]];
       
        cell.jiaocaiBlock = ^{
            [self changeBook];
        };
        
        cell.changeBlock = ^{
            [self changeUnit];
        };
        cell.hidden = self.currentBook==nil;
        return cell;
    }
    
    return nil;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2) {
        //        StarterModuleViewController *vc = [[StarterModuleViewController alloc] init];
        //        vc.unitModel = self.currentUnit;
        //        [self.navigationController pushViewController:vc animated:YES];
        if (!lApp.isVip) {
            UIViewController *vc = [[UIViewController alloc] initWithClassName:@"VipCenterBookDetailVC"];
            vc.paraObject = lApp.bookid;
            [(BaseNavigationController *)lApp.window.rootViewController pushViewController:vc animated:YES];
            return;
        }
        
        NSString *url = [NSString stringWithFormat:@"%@parame=&id=%@&title=%@",H5_API_vocabularyList,self.currentUnit.unitid,[self.currentUnit.name stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]]];
       
        [MethodTool goWebviewWithUrl:url];
    }
}

- (void)changeBook {
    [GradeChooseView chooseGradeWithBooks:self.bookList Complection:^(HSchildrenBookModel * _Nonnull model) {
        self.currentBook = model;
        [self.tableView reloadData];
        [self loadBookUnitData];
    }];
    
}

- (void)changeUnit {
    [HomeRequest getTextBookUnitWithId:self.currentBook.versionId Result:^(NSMutableArray<HSTextBookUnitModel *> *list) {
        if(list.count){
            self.currentUnit = list.firstObject;
            [ModuleChooseView chooseModulenWithUnits:list book:self.currentBook Complection:^(HSTextBookUnitModel *unitModel) {
                self.currentUnit = unitModel;
                [self.tableView reloadData];
            }];
        }
    }];
    
}

- (void)loadBookListData {
    [HomeRequest getTextBookWithResult:^(NSMutableArray<HSTextBookModel *> *list) {
        if(list.count){
            self.bookList = list;
            HSTextBookModel *book =  list.firstObject;
            if(book.children.count){
                self.currentBook = book.children.firstObject;
                [self loadBookUnitData];
            }
            [self.tableView reloadData];
        }
        
    }];
}
- (void)LoadInfo
{
    [MineAPIManager GetUserInformationWithParam:@{} result:^(NSDictionary * _Nonnull dic) {
        NSDictionary *data = dic[@"data"];
       
        lApp.schoolName = data[@"school"][@"name"];
        lApp.gradeName  = data[@"grade"][@"gradeName"];
       
    }];
}
- (void)loadBookUnitData {
    [HomeRequest getTextBookUnitWithId:self.currentBook.versionId Result:^(NSMutableArray<HSTextBookUnitModel *> *list) {
        if(list.count){
            self.currentUnit = list.firstObject;
            [self.tableView reloadData];
        }
        [self LoadInfo];
    }];
}
- (void)checkVersion
{
    [MineAPIManager CheckVersionWithParam:@{@"platform":@"ios",@"current_version":[MethodTool appVersion]} result:^(NSDictionary * _Nonnull dic) {
       
        if ([dic[@"data"] isKindOfClass:[NSDictionary class]]) {
            NSDictionary *adic =  dic[@"data"];
            if(adic.allValues.count != 0)
            {
                [MethodTool checkVersionUpdateWithInfo:adic];
            }
        }
        [self getdataFromServer];
    }];
}
@end
